package com.tingyuge.thinking.spring.event;

import java.util.EventListener;
import java.util.EventObject;
import java.util.Observable;
import java.util.Observer;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/12/12
 * @description
 * @see java.util.Observable
 */
public class ObserverDemo {


    public static void main(String[] args) {
        EventObservable observable = new EventObservable();
        //添加观察者(监听者)
        observable.addObserver(new EventObserver());
        //发布消息(事件)
        observable.notifyObservers("hello 各位");

    }

    static class EventObservable extends Observable{
        @Override
        protected synchronized void setChanged() {
            super.setChanged();
        }

        @Override
        public void notifyObservers(Object arg) {
            setChanged();
            super.notifyObservers(new EventObject(arg));
            clearChanged();
        }
    }

    static class EventObserver implements Observer, EventListener {

        @Override
        public void update(Observable o, Object message) {
            EventObject eventObject = (EventObject) message;
            System.out.println("收到事件: "+ eventObject);
        }
    }
}
